queue = collections.deque() queue.append(root) res = [] while queue: size = len(queue) level = [] for _ in range(size): cur = queue.popleft() ifnot cur: continue level.append(cur.val) queue.append(cur.left) queue.append(cur.right) if level: res.append(level) return res
nodes = [(root,)] values = [] while nodes: values.append([r.val for n in nodes for r in n if r]) nodes = [(r.left, r.right) for n in nodes for r in n if r] return values[:-1]
stack = [] p = root pre = None while p or stack: while p: stack.append(p) p = p.left p = stack.pop() if pre and p.val <= pre.val: returnFalse pre = p p = p.right returnTrue
# delete from the right subtree if key > root.val: root.right = self.deleteNode(root.right, key) # delete from the left subtree elif key < root.val: root.left = self.deleteNode(root.left, key) # delete the current node else: # the node is a leaf ifnot (root.left or root.right): root = None # the node is not a leaf and has a right child elif root.right: root.val = self.successor(root) root.right = self.deleteNode(root.right, root.val) # the node is not a leaf, has no right child, and has a left child else: root.val = self.predecessor(root) root.left = self.deleteNode(root.left, root.val)
defcompute_depth(self, node: TreeNode) -> int: """ Return tree depth in O(d) time. """ d = 0 while node.left: node = node.left d += 1 return d
defexists(self, idx: int, d: int, node: TreeNode) -> bool: """ Last level nodes are enumerated from 0 to 2**d - 1 (left -> right). Return True if last level node idx exists. Binary search with O(d) complexity. """ left, right = 0, 2**d - 1 for _ in range(d): pivot = left + (right - left) // 2 if idx <= pivot: node = node.left right = pivot else: node = node.right left = pivot + 1 return node isnotNone
defcountNodes(self, root: TreeNode) -> int: # if the tree is empty ifnot root: return0
d = self.compute_depth(root) # if the tree contains 1 node if d == 0: return1
# Last level nodes are enumerated from 0 to 2**d - 1 (left -> right). # Perform binary search to check how many nodes exist. left, right = 1, 2**d - 1 while left <= right: pivot = left + (right - left) // 2 if self.exists(pivot, d, root): left = pivot + 1 else: right = pivot - 1
# The tree contains 2**d - 1 nodes on the first (d - 1) levels # and left nodes on the last level. return (2**d - 1) + left